package com.wcbdota.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wcbdota.R;
import com.wcbdota.base.BaseMessage;
import com.wcbdota.base.BaseUi;
import com.wcbdota.base.C;
import com.wcbdota.base.Messages;
import com.wcbdota.model.Hero;
import com.wcbdota.model.HeroBackground;
import com.wcbdota.model.HeroProperty;
import com.wcbdota.model.HeroSkillSequence;
import com.wcbdota.model.Skill;
import com.wcbdota.util.AppUtil;
import com.wcbdota.util.AsyncImageLoader;
import com.wcbdota.util.AsyncImageLoader.ImageCallback;
import com.wcbdota.util.SDUtil;

@SuppressWarnings("unchecked")
public class UiHeroDetail extends BaseUi {

	private static String TAG = UiHero.class.getSimpleName();
	DisplayMetrics metric = new DisplayMetrics();

	int width = 0;
	int lineSkillItemNum = 0;
	int lineNum = -1;
	
	private TextView pt_tv_titlename;

	private ArrayList<Skill> SkillObjList = new ArrayList<Skill>();
	private ArrayList<HeroProperty> PropertyObjList = new ArrayList<HeroProperty>();
	private ArrayList<HeroSkillSequence> SkillSequenceObjList = new ArrayList<HeroSkillSequence>();
	private ArrayList<HeroBackground> BackgroundObjList = new ArrayList<HeroBackground>();

	private Hero hero;

	private ImageButton[] skillitem = null;
	private Button[] skillsequencetype = null;
	private ImageButton[] skillsequenceitem = null;

	private String[] positions = { "核心", "控制", "对线辅助", "先手", "打野", "辅助", "耐久",
			"爆发", "推进", "逃生" };

	//private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
	HashMap<String, String> urlParams = new HashMap<String, String>();

	private ImageView hd_iv_heroico; // 显示英雄头像
	private TextView hd_tv_heroname; // 显示英雄名称
	private TextView hd_tv_heroposition; // 显示英雄位置
	private TextView hd_tv_heroattribute; // 显示英雄基础属性

	private TextView hd_tv_backgroundstory; // 显示英雄背景故事

	private LinearLayout hd_LinearLayout_skillitem; // 显示英雄技能图标的线性布局
	private TextView hd_tv_skilldetail; // 显示技能详细信息

	private RelativeLayout hd_RelativeLayout_skillsequence;
	private LinearLayout hd_LinearLayout_skillsequencetype; // 显示英雄技能加点路线种类的线性布局
	private RelativeLayout hd_RelativeLayout_skillsequenceitem; // 技能图标序列
	private TextView hd_tv_skillsequencementtality; // 技能加点心得

	private int hd_bt_addskillpoint_check = 0;
	private int hd_bt_baseproperty_check = 0;
	private int hd_bt_history_check = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hero_detail);
		if(InitScream()==true){
			System.out.println(InitScream()+"");
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
		}
		init();
		
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels;
		lineSkillItemNum = width / 50;
		Log.i("屏幕宽度", ""+width+" "+lineSkillItemNum);
		hero = (Hero) getIntent().getSerializableExtra("hero");
		urlParams.put("heroid", hero.getId().toString());

		this.doTaskAsync(C.task.heroSkillList, C.api.heroSkillList, urlParams);
		this.doTaskAsync(C.task.heroPropertyList, C.api.heroPropertyList,
				urlParams);
		this.doTaskAsync(C.task.heroBackground, C.api.heroBackground, urlParams);
		this.doTaskAsync(C.task.heroSkillSequence, C.api.heroSkillSequence,
				urlParams);

		String imageUrl = C.remoteres.base + C.remoteres.heroes + "/"
				+ hero.getAvatar() + ".png";
		String cacheKey = AppUtil.md5(imageUrl);
		Bitmap bitmap = SDUtil.getImage(cacheKey);
		hd_iv_heroico.setImageBitmap(bitmap);

		// 拼接英雄名称信息 #ecbd6b
		String HeroName = "<font color=\"#ecbd6b\">英雄名称：" + hero.getHeroName()
				+ "</font>" + "<font color=\"#b22b4c\">" + " ("
				+ hero.getNickName() + ")" + "</font>";
		hd_tv_heroname.setText(Html.fromHtml(HeroName));

		// 拼接英雄位置信息
		String[] positionArray = hero.getPosition().split(",");
		String pos = "<font color=\"#ecbd6b\">英雄定位：</font>"
				+ "<font color=\"#008acf\">";
		for (int i = 0; i < positionArray.length; i++) {
			pos += positions[Integer.valueOf(positionArray[i]) - 1];
			if (i != positionArray.length - 1) {
				pos += "，";
			}
		}
		pos += "</font>";
		hd_tv_heroposition.setText(Html.fromHtml(pos));
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// async task callback methods

	@Override
	public void onTaskComplete(int taskId, BaseMessage message) {
		super.onTaskComplete(taskId, message);

		switch (taskId) {
		case C.task.heroSkillList:
			try {
				// 将msg对象保存至全局存储
				Messages.msg.msg_UiHeroDetail_HeroSkill = message;
				Skillinit();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		case C.task.heroPropertyList:
			try {
				// 将msg对象保存至全局存储
				Messages.msg.msg_UiHeroDetail_HeroProperty = message;
				Propertyinit();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		case C.task.heroSkillSequence:
			try {
				// 将msg对象保存至全局存储
				Messages.msg.msg_UiHeroDetail_HeroSkillSequence = message;
				HeroSkillSequenceinit();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		case C.task.heroBackground:
			try {
				// 将msg对象保存至全局存储
				Messages.msg.msg_UiHeroDetail_HeroBackground = message;
				HeroBackgroundinit();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	public void onNetworkError(int taskId) {
		super.onNetworkError(taskId);
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// other methods

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	public void init() {
		findViewById(R.id.pt_bt_back).setOnClickListener(mOnClickListener);
		findViewById(R.id.pt_bt_reload).setOnClickListener(mOnClickListener);
		pt_tv_titlename = (TextView) findViewById(R.id.pt_tv_titlename);
		pt_tv_titlename.setText("英雄详情");

		hd_iv_heroico = (ImageView) findViewById(R.id.hd_iv_heroico);
		hd_tv_heroname = (TextView) findViewById(R.id.hd_tv_heroname);
		hd_tv_heroposition = (TextView) findViewById(R.id.hd_tv_heroposition);
		hd_tv_heroattribute = (TextView) findViewById(R.id.hd_tv_heroattribute);

		hd_LinearLayout_skillitem = (LinearLayout) findViewById(R.id.hd_LinearLayout_skillitem);
		hd_tv_skilldetail = (TextView) findViewById(R.id.hd_tv_skilldetail);

		hd_RelativeLayout_skillsequence = (RelativeLayout) findViewById(R.id.hd_RelativeLayout_skillsequence);
		hd_LinearLayout_skillsequencetype = (LinearLayout) findViewById(R.id.hd_LinearLayout_skillsequencetype);
		hd_RelativeLayout_skillsequenceitem = (RelativeLayout) findViewById(R.id.hd_RelativeLayout_skillsequenceitem);
		hd_tv_skillsequencementtality = (TextView) findViewById(R.id.hd_tv_skillsequencementtality);

		hd_tv_backgroundstory = (TextView) findViewById(R.id.hd_tv_backgroundstory);

		findViewById(R.id.hd_bt_addskillpoint).setOnClickListener(
				mOnClickListener);
		findViewById(R.id.hd_bt_baseproperty).setOnClickListener(
				mOnClickListener);
		findViewById(R.id.hd_bt_history).setOnClickListener(mOnClickListener);
	}

	public void Skillinit() {
		try {
			SkillObjList = (ArrayList<Skill>) Messages.msg.msg_UiHeroDetail_HeroSkill
					.getResultList("Skill");
			hd_tv_skilldetail.setText(Html.fromHtml(getSkilldetail(SkillObjList
					.get(0))));
			skillitem = new ImageButton[SkillObjList.size()];
			for (int i = 0; i < SkillObjList.size(); i++) {
				CreateSkillItem(i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void Propertyinit() {
		try {
			PropertyObjList = (ArrayList<HeroProperty>) Messages.msg.msg_UiHeroDetail_HeroProperty
					.getResultList("HeroProperty");
			hd_tv_heroattribute.setText(Html
					.fromHtml(getPropertydetail(PropertyObjList.get(0))));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void HeroSkillSequenceinit() {
		try {
			SkillSequenceObjList = (ArrayList<HeroSkillSequence>) Messages.msg.msg_UiHeroDetail_HeroSkillSequence
					.getResultList("HeroSkillSequence");
			skillsequencetype = new Button[SkillSequenceObjList.size()];
			skillsequenceitem = new ImageButton[25];
			for(int i = 0; i < SkillSequenceObjList.size(); i++) {
				CreateSkillSequenceType(i);
			}
			for(int i = 0; i < 25; i++){
				CreateSkillSequenceItem(i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void HeroBackgroundinit() {
		try {
			BackgroundObjList = (ArrayList<HeroBackground>) Messages.msg.msg_UiHeroDetail_HeroBackground
					.getResultList("HeroBackground");
			hd_tv_backgroundstory.setText(Html
					.fromHtml(getHeroBackground(BackgroundObjList.get(0))));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void CreateSkillItem(int num) {
		skillitem[num] = new ImageButton(app);
		skillitem[num].setId(2000 + num);
		String imageUrl = C.remoteres.base + C.remoteres.heroes
				+ C.remoteres.heroes_abilities + "/"
				+ SkillObjList.get(num).getPic() + ".png";
		HashMap<String, Object> hashmap = new HashMap<String, Object>();
		hashmap.put("index", num);
		hashmap.put("imageUrl", imageUrl);
		skillitem[num].setTag(hashmap);
		skillitem[num].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HashMap<String, Object> hashmap = new HashMap<String, Object>();
				hashmap = (HashMap<String, Object>) v.getTag();
				hd_tv_skilldetail.setText(Html
						.fromHtml(getSkilldetail(SkillObjList
								.get((Integer) hashmap.get("index")))));
			}
		});
		LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(100, 100);

		hd_LinearLayout_skillitem.addView(skillitem[num], p); // 将按钮放入layout组件
		// LoadSkillItemImg(SkillObjList.get(num).getPic());
		LoadSkillItemImg(C.remoteres.base + C.remoteres.heroes
				+ C.remoteres.heroes_abilities + "/" + SkillObjList.get(num).getPic() + ".png", skillitem[num]);
	}

	public void CreateSkillSequenceType(int num) {
		skillsequencetype[num] = new Button(app);
		skillsequencetype[num].setId(3000 + num);
		skillsequencetype[num].setText(SkillSequenceObjList.get(num)
				.getSequenceName());
		HashMap<String, Object> hashmap = new HashMap<String, Object>();
		hashmap.put("index", num);
		skillsequencetype[num].setTag(hashmap);
		skillsequencetype[num].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HashMap<String, Object> hashmap = new HashMap<String, Object>();
				hashmap = (HashMap<String, Object>) v.getTag();
				String[] skillsequence = SkillSequenceObjList
						.get((Integer) hashmap.get("index")).getSkillSequence()
						.split(",");
				for (int i = 0; i < skillsequence.length; i++) {
					UpdateSkillSequenceItemImage(i, Integer.valueOf(skillsequence[i]));
				}

				String sequencementtality = "<font color=\"red\">加点思路：</font>"
						+ "<br />"
						+ SkillSequenceObjList.get(
								(Integer) hashmap.get("index")).getMentality();

				hd_tv_skillsequencementtality.setText(Html
						.fromHtml(sequencementtality));
			}
		});
		LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 70);

		hd_LinearLayout_skillsequencetype.addView(skillsequencetype[num], p); // 将按钮放入layout组件
	}

//	public void CreateSkillSequenceItem(int num, int skillid) {
//		skillsequenceitem[num] = new ImageButton(app);
//		skillsequenceitem[num].setId(4000 + num);
//		RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(50, 50);
//		p.leftMargin = num * 50 + 2;
//		if( (num+1)%lineSkillItemNum == 0){
//			p.topMargin = 50 * lineNum;
//			lineNum++;
//		}
//		
//		int skillnum = skillid - 1;
//		
//		if (skillnum < 0) {
//			skillsequenceitem[num].setBackgroundResource(R.drawable.levelup);
//			//LoadSkillItemImg(C.remoteres.base + C.remoteres.property + "/levelup" + ".jpg",skillsequenceitem[num]);
//		} else {
//			LoadSkillItemImg(C.remoteres.base + C.remoteres.heroes
//					+ C.remoteres.heroes_abilities + "/" + SkillObjList.get(skillnum).getPic() + ".png",skillsequenceitem[num]);
//		}
//		
//		hd_RelativeLayout_skillsequenceitem.addView(skillsequenceitem[num], p); // 将按钮放入layout组件
//	}
	
	public void CreateSkillSequenceItem(int num) {
		skillsequenceitem[num] = new ImageButton(app);
		skillsequenceitem[num].setId(4000 + num);
		RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(50, 50);
//		p.leftMargin = num * 50 + 2;
//		if( (num+1)%lineSkillItemNum == 0){
//			p.leftMargin = 
//			p.topMargin = 50 * lineNum;
//			lineNum++;
//		}
		
		if (num%9 == 0) {
			lineNum++;
	    }
		p.leftMargin = 2 + 50 * (num%9);   //横坐标定位        
		p.topMargin = 2 + 50 * lineNum;   //纵坐标定位
		
		hd_RelativeLayout_skillsequenceitem.addView(skillsequenceitem[num], p); // 将按钮放入layout组件
	}
	
	public void UpdateSkillSequenceItemImage(int num, int SkillIndex){
		int skillnum = SkillIndex - 1;
		
		if (skillnum < 0) {
			skillsequenceitem[num].setBackgroundResource(R.drawable.levelup);
			//LoadSkillItemImg(C.remoteres.base + C.remoteres.property + "/levelup" + ".jpg",skillsequenceitem[num]);
		} else {
			LoadSkillItemImg(C.remoteres.base + C.remoteres.heroes
					+ C.remoteres.heroes_abilities + "/" + SkillObjList.get(skillnum).getPic() + ".png",skillsequenceitem[num]);
		}
	}

	public void LoadSkillItemImg(String pic, View view) {
		String imageUrl = pic;
		String cacheKey = AppUtil.md5(imageUrl);
		Bitmap cachedImage = SDUtil.getImage(cacheKey);
		if (cachedImage == null) {
			AsyncImageLoader asyncImageLoader = new AsyncImageLoader(view);
			cachedImage = asyncImageLoader.loadBitmap(imageUrl,
					new ImageCallback() {
				HashMap<String, Object> hashmap = new HashMap<String, Object>();
	
				@Override
				public void imageLoadSuccess(Bitmap imageBitmap,
						String imageUrl, View view) {
					String cacheKey = AppUtil.md5(imageUrl);
					SDUtil.saveImage(imageBitmap, cacheKey);
					((ImageView) view).setImageBitmap(imageBitmap);
					return;
				}
	
				@Override
				public void imageLoadError(String imageUrl, View view) {
					for (int i = 0; i < skillitem.length; i++) {
						hashmap = (HashMap<String, Object>) skillitem[i]
								.getTag();
						if (hashmap.get("imageUrl").toString()
								.equals(imageUrl)) {
							skillitem[i]
									.setImageResource(R.drawable.img_loading_error);
							return;
						}
					}
				}
			});
		} else {
			((ImageView) view).setImageBitmap(cachedImage);
		}
	}

	public String getHeroBackground(HeroBackground herobackground) {
		String BackgroundText = "";
		BackgroundText += herobackground.getSummary();
		return BackgroundText;
	}

	public String getPropertydetail(HeroProperty heroproperty) {
		String PropertyText = "";
		String[] BasePropertyArray = heroproperty.getBaseProperty().split(",");
		PropertyText = "HP:" + BasePropertyArray[0] + "&emsp;" + "MP:"
				+ BasePropertyArray[1] + "<br />" + "力量:"
				+ BasePropertyArray[2] + "&emsp;" + "攻击:"
				+ BasePropertyArray[5] + "<br />" + "敏捷:"
				+ BasePropertyArray[3] + "&emsp;" + "移动:"
				+ BasePropertyArray[6] + "<br />" + "智力:"
				+ BasePropertyArray[4] + "&emsp;" + "护甲:"
				+ BasePropertyArray[7];
		return PropertyText;
	}

	public String getSkilldetail(Skill skill) {
		String skilltext = "";

		skilltext += skill.getSkillName() + "<br />";
		skilltext += "快捷键:" + "<font color=\"red\">" + skill.getKeyboard()
				+ "</font>" + "<br />";
		skilltext += skill.getDesc() + "<br /><br />";

		// 固定效果
		String[] FPropertArray = skill.getFPropertyArray().split(",");
		String[] FPropertValues = skill.getFPropertyValues().split(",");
		if(FPropertArray.length > 0){
			for (int i = 0; i < FPropertArray.length; i++) {
				skilltext += FPropertArray[i] + ":" + FPropertValues[i] + "<br />";
			}
		}
		
		skilltext += "<br />";

		// 随技能级别成长的效果
		String[] GPropertArray = skill.getGPropertyArray().split(",");
		String[] GPropertValues = skill.getGPropertyValues().split(",");
		HashMap<String, Object> GPropert = new HashMap<String, Object>();
		int skillLevel = 0;
		if(GPropertArray.length > 0){
			for (int i = 0; i < GPropertArray.length; i++) {
				String[] GPropertValuesLevel = GPropertValues[i].split("/");
				skillLevel = GPropertValuesLevel.length;
				GPropert.put(GPropertArray[i], GPropertValuesLevel);
			}
			for (int i = 0; i < skillLevel; i++) {
				int level = i + 1;
				skilltext += "<font color=\"green\">等级" + level + ":</font>";
				for (int j = 0; j < GPropertArray.length; j++) {
					String[] temp = (String[]) GPropert.get(GPropertArray[j]);
					skilltext += GPropertArray[j] + ":" + temp[i] + " ";
				}
				skilltext += "<br />";
			}
		}
		return skilltext;
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// Listener

	OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.pt_bt_back:
				finish();
				break;
			case R.id.pt_bt_reload:
				toast("已是最新数据 :) ");
				break;
			case R.id.hd_bt_addskillpoint:
				if (hd_bt_addskillpoint_check == 0) {
					hd_bt_addskillpoint_check = 1;
					hd_RelativeLayout_skillsequence.setVisibility(View.VISIBLE);
				} else {
					hd_bt_addskillpoint_check = 0;
					hd_RelativeLayout_skillsequence.setVisibility(View.GONE);
				}
				break;
			case R.id.hd_bt_baseproperty:
				if (hd_bt_baseproperty_check == 0) {
					hd_bt_baseproperty_check = 1;
					toast("该功能正在努力开发中，敬请期待。。。");
				} else {
					hd_bt_baseproperty_check = 0;
				}
				break;
			case R.id.hd_bt_history:
				if (hd_bt_history_check == 0) {
					hd_bt_history_check = 1;
					hd_tv_backgroundstory.setVisibility(View.VISIBLE);
				} else {
					hd_bt_history_check = 0;
					hd_tv_backgroundstory.setVisibility(View.GONE);
				}
				break;
			}
		}
	};
}
